package com.schoolgard.action.configuration;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.schoolegard.services.ParamServerService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.ParamServerToDevice;
import com.supersystem.utils.DateJsonValueProcessor;
import com.supersystem.utils.DateUtil;

public class ParamServerJobAction extends BaseAction {
	private ParamServerService paramServerService;

	public ParamServerToDevice serverToDevice;

	public void findAll() {
		try {
			String startStr = request.getParameter("start"); // grid传过来的当前数据条数
			String limitStr = request.getParameter("limit"); // 每页显示的数据数

			int start = Integer.parseInt(startStr);
			int limit = Integer.parseInt(limitStr);
			if (limit == 0) {
				limit = Integer.MAX_VALUE;
			}
			GridDataModel<ParamServerToDevice> page = paramServerService.findAllJob(constractBean(), start, limit);
			JsonValueProcessor jsonProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(Date.class, jsonProcessor);
			String jsonStr = JSONObject.fromObject(page, config).toString();
			writeToResponse(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private ParamServerToDevice constractBean() throws ParseException{
		ParamServerToDevice toDevice = new ParamServerToDevice();
		String id = request.getParameter("deviceId");
		String time = request.getParameter("queryTime");
		Date date = DateUtil.parseDate(DateUtil.format(new Date()));
		if(StringUtils.isNotEmpty(id)) {
			id = id.replace("de_", "");
			toDevice.setGuid(id);
		}
		if("9".equals(time)){
			toDevice.setCreateDatetime(null);
			toDevice.setFinishDatetime(null);
		}else if("1".equals(time)){
			toDevice.setFinishDatetime(DateUtils.addDays(date,-7));
		}else{
			toDevice.setCreateDatetime(DateUtils.addDays(date, -7));
			toDevice.setFinishDatetime(date);
		}
		return toDevice;
	}

	public ParamServerToDevice getServerToDevice() {
		return serverToDevice;
	}

	public void setServerToDevice(ParamServerToDevice serverToDevice) {
		this.serverToDevice = serverToDevice;
	}

	public void setParamServerService(ParamServerService paramServerService) {
		this.paramServerService = paramServerService;
	}
}
